<?php

namespace app\model;

use Laf\Log;
use mon\orm\Model;
use mon\util\Instance;
use mon\orm\exception\DbException;

/**
 * 图文信息绑定App表模型
 *
 * Class ChatAccessModel
 * @copyright 2021-04-18 mon-console
 * @version 1.0.0
 */
class ChatAccessModel extends Model
{
    use Instance;

    /**
     * 操作表
     *
     * @var string
     */
    protected $table = 'chat_access';

    /**
     * 新增自动写入字段
     *
     * @var array
     */
    protected $insert = ['create_time', 'update_time'];

    /**
     * 更新自动写入字段
     *
     * @var array
     */
    protected $update = ['update_time'];

    /**
     * 验证器
     *
     * @var string
     */
    protected $validate = \app\validate\Chat::class;

    /**
     * 获取客服账号绑定的APP列表
     *
     * @param integer $waiter_id
     * @return array
     */
    public function getBindApp($waiter_id)
    {
        $result = $this->alias('a')->join(ChatAppModel::instance()->getTable() . ' b', 'a.app_id = b.id')->where('a.waiter_id', $waiter_id)
            ->field('a.waiter_id, a.app_id, b.`name`, b.title, b.status')->select();
        return $result;
    }

    /**
     * 绑定APP
     *
     * @param array $data
     * @return boolean
     */
    public function bind($data)
    {
        $check = $this->validate()->data($data)->scope('bind')->check();
        if ($check !== true) {
            $this->error = $this->validate()->getError();
            return false;
        }
        $this->startTrans();;
        try {
            // 移除旧绑定数据
            $del = $this->where('waiter_id', $data['idx'])->delete();
            if ($del === false) {
                $this->rollback();
                $this->error = '更新关联数据失败';
                return false;
            }
            // 重新绑定
            $apps = explode(',', $data['apps']);
            $saveData = [];
            $now = time();
            foreach ($apps as $app_id) {
                $saveData[] = [
                    'waiter_id' => $data['idx'],
                    'app_id'    => $app_id,
                    'update_time' => $now,
                    'create_time' => $now,
                ];
            }

            $save = $this->insertAll($saveData);
            if (!$save) {
                $this->rollback();
                $this->error = '保存关联数据失败';
                return false;
            }

            $this->commit();
            return true;
        } catch (DbException $e) {
            $this->rollback();
            $this->error = '关联APP异常！';
            Log::instance()->error($this->error . $e->getMessage());
            return false;
        }
    }

    /**
     * 自动完成create_time字段
     * 
     * @param mixed $val 默认值
     * @param array  $row 列值
     * @return string
     */
    protected function setCreateTimeAttr($val)
    {
        return time();
    }

    /**
     * 自动完成update_time字段
     * 
     * @param mixed $val 默认值
     * @param array  $row 列值
     * @return string
     */
    protected function setUpdateTimeAttr($val)
    {
        return time();
    }
}
